import { PageContainer } from '@ant-design/pro-layout';
import { Button, message, Modal, Spin, Table } from 'antd';
import { FormattedMessage } from 'umi';
import ProTable from '@ant-design/pro-table';
import ProForm, { DrawerForm, ModalForm, ProFormDatePicker, ProFormDigit, ProFormSelect, ProFormText, ProFormTextArea, ProFormUploadDragger } from '@ant-design/pro-form';
import React, { useState, useRef, useEffect } from 'react';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import { FileExcelOutlined, PlusOutlined } from '@ant-design/icons';
import { GiftType } from '../../../model';
import { giftListData, saveGift, giftNowListData, productList, giftEdit, giftOverdue } from '../service';
import DealerDialog from '@/components/Common/DealerDialog';
import { exportFile } from '@/utils/utils';
import request from '@/utils/request';
export default (() => {
  const access: string = (sessionStorage.getItem('access') as string);
  const [showCreate, setShowCreate] = useState(false);
  const actionRef = useRef<ActionType>();
  const formRef = React.createRef<any>();
  const [activeKey, setActiveKey] = useState('tab0');
  const [editFlag, setEditFlag] = useState(false);
  const [showImport, setShowImport] = useState<boolean>(false);
  const [errorVisible, setErrorVisible] = useState<boolean>(false);
  const [errInfo, setErrInfo] = useState<any[]>([]);
  const [dealDialog, setDealDialog] = useState<boolean>(false);
  const [dealer, setDealer] = useState<{}>({});
  const [nameOption, setNameOption] = useState<[]>([]);
  const [codeOption, setCodeOption] = useState<[]>([]);
  const [proData, setProData] = useState<{}>({});
  const [editModel, setEditModel] = useState<{}>({});
  const JXS_FLAG = (sessionStorage.getItem('access') as string) === 'jxs-1';
  const [spinningFlag, setSpinningFlag] = useState(false);

  async function productData() {
    var res = await productList({
      pageSize: 1000
    });
    var obj = {};
    var proData = {};
    res.data.forEach((item: any) => {
      if (!proData[item.product_name]) {
        proData[item.product_name] = [];
      }

      proData[item.product_name].push({
        label: item.product_standard,
        value: item.product_standard
      });
    });
    setProData(proData);
    var rData = res.data.reduce(function (item: any, next: any) {
      if (!obj[next.product_name]) {
        obj[next.product_name] = {
          text: next.product_name
        };
        item.push(next);
      }

      return item;
    }, []);
    setNameOption(rData.map((item: any) => {
      return {
        label: item.product_name,
        value: item.product_name
      };
    }));
  }

  useEffect(() => {
    productData();
    return function cleanup() {};
  }, []);

  function export1(params: any) {
    return request('/xwyl/dealerGift/exportGiftAll', {
      method: 'POST',
      requestType: 'form',
      data: { ...params,
        method: 'post'
      }
    });
  }

  function export2(params: any) {
    return request('/xwyl/dealerGift/exportGiftNow', {
      method: 'POST',
      requestType: 'form',
      data: { ...params,
        method: 'post'
      }
    });
  }

  function export3(params: any) {
    return request('/xwyl/dealerGift/exportGiftOverdue', {
      method: 'POST',
      requestType: 'form',
      data: { ...params,
        method: 'post'
      }
    });
  }

  const errorColumn = [{
    title: '错误行',
    dataIndex: 'rownum'
  }, {
    title: '错误信息',
    dataIndex: 'errerMsg'
  }]; //表头信息以及表值设置

  const columns: ProColumns<GiftType>[] = [// {
  //   title: '状态',
  //   dataIndex: 'status',
  //   width:100,
  //   valueType:'select',
  //   valueEnum:{
  //     1:{text:'生效'},
  //     2:{text:'失效'}
  //   }
  // },
  {
    title: '客户代码',
    dataIndex: 'dealerCode',
    width: 100,
    hideInSearch: JXS_FLAG,
    hideInTable: JXS_FLAG,
    editable: false
  }, {
    title: '客户名称',
    hideInSearch: JXS_FLAG,
    dataIndex: 'dealerName',
    editable: false,
    width: 200,
    hideInTable: JXS_FLAG,
    ellipsis: true
  }, {
    title: '产品名称',
    width: 200,
    ellipsis: true,
    dataIndex: 'productName'
  }, {
    title: '产品型号',
    width: 200,
    ellipsis: true,
    dataIndex: 'productStandard'
  }, {
    title: '订单号',
    hideInSearch: activeKey === 'tab1',
    width: 150,
    ellipsis: true,
    dataIndex: 'orderNumber',
    hideInTable: activeKey === 'tab1'
  }, {
    title: '数量',
    hideInSearch: true,
    width: 150,
    dataIndex: 'productNum'
  }, {
    title: '截止日期',
    hideInSearch: true,
    valueType: 'date',
    width: 150,
    dataIndex: 'effectData'
  }, {
    title: '创建日期',
    hideInSearch: true,
    valueType: 'date',
    hideInTable: activeKey === 'tab1',
    width: 150,
    dataIndex: 'createTime'
  }, {
    title: '备注',
    hideInSearch: true,
    width: 200,
    hideInTable: activeKey === 'tab1',
    ellipsis: true,
    dataIndex: 'remark'
  }, {
    title: '操作',
    key: 'option',
    width: 100,
    valueType: 'option',
    fixed: 'right',
    hideInTable: activeKey === 'tab1' || JXS_FLAG,
    render: (_, record: any) => [<a key='show' hidden={record.action === 'delete'||access==='analysis'} onClick={() => {
      setEditFlag(true);
      setEditModel(record);
    }} >修改</a>]
  }];

  const onFileUpload = (info: any) => {
    if (info.file.status !== 'uploading') {}

    if (info.file.status === 'done') {
      if (info.file.response.errorCode === '200') {
        message.success(`${info.file.name} 上传成功，后台正在处理...`);
        actionRef.current?.reloadAndRest?.();
        setShowImport(false);
      } else {
        message.error('上传失败: ' + info.file.response.msg);
        setErrorVisible(true);
        setErrInfo(info.file.response.data);
      }
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} 上传失败！`);
    }
  };

  const handleCancel = () => {
    setErrorVisible(false);
    setErrInfo([]);
  };

  return <PageContainer>
    <ProTable<GiftType> scroll={{
      x: 1300
    }} actionRef={actionRef} toolbar={{
      menu: {
        type: 'tab',
        activeKey: activeKey,
        items: [{
          key: 'tab0',
          label: <span>全部</span>
        }, {
          key: 'tab1',
          label: <span>剩余</span>
        }, {
          key: 'tab2',
          label: <span>失效</span>
        }],
        onChange: key => {
          setActiveKey((key as string));
          actionRef.current?.reloadAndRest?.();
        }
      },
      settings: []
    }} request={(params, sorter, filter) => {
      if (activeKey === 'tab0') return giftListData({ ...params,
        filter
      });
      if (activeKey === 'tab1') return giftNowListData({ ...params,
        filter
      });
      return giftOverdue({ ...params,
        filter
      });
    }} pagination={{
      pageSizeOptions: ['20', '100', '500']
    }} columns={columns} rowKey='id' search={{
      span: 9,
      defaultCollapsed: false,
      optionRender: ({
        searchText,
        resetText
      }, {
        form
      }) => [<Button key='search' type='primary' onClick={() => {
        form?.submit();
      }} >
              {searchText}
            </Button>, <Button key='rest' onClick={() => {
        form?.resetFields();
        form?.submit();
      }}>
              {resetText}
            </Button>, <Button type='primary' key='import' hidden={access === 'jxs-1'} onClick={async () => {
        setSpinningFlag(true);
        var params: any = {};
        params.dealerCode = form?.getFieldValue('dealerCode');
        params.dealerName = form?.getFieldValue('dealerName');
        params.productName = form?.getFieldValue('productName');
        var val = await export1(params);

        if (val.errorCode === '200') {
          exportFile(val.data, '全部赠品.xlsx');
        } else {
          message.error(val.errorMessage);
        }

        setSpinningFlag(false);
      }}>
              全部导出
          </Button>, <Button type='primary' key='import' hidden={access === 'jxs-1'} onClick={async () => {
        setSpinningFlag(true);
        var params: any = {};
        params.dealerCode = form?.getFieldValue('dealerCode');
        params.dealerName = form?.getFieldValue('dealerName');
        params.productName = form?.getFieldValue('productName');
        var val = await export2(params);

        if (val.errorCode === '200') {
          exportFile(val.data, '剩余赠品.xlsx');
        } else {
          message.error(val.errorMessage);
        }

        setSpinningFlag(false);
      }}>
            剩余导出
        </Button>, <Button type='primary' key='import' hidden={access === 'jxs-1'} onClick={async () => {
        setSpinningFlag(true);
        var params: any = {};
        params.dealerCode = form?.getFieldValue('dealerCode');
        params.dealerName = form?.getFieldValue('dealerName');
        params.productName = form?.getFieldValue('productName');
        var val = await export3(params);

        if (val.errorCode === '200') {
          exportFile(val.data, '失效赠品.xlsx');
        } else {
          message.error(val.errorMessage);
        }

        setSpinningFlag(false);
      }} >
          失效导出
      </Button>]
    }} toolBarRender={() => JXS_FLAG ? [] : [<Button hidden={access==='analysis'} type='primary' key='primary' onClick={() => {
      setShowCreate(true);
    }}>
          <PlusOutlined/> <FormattedMessage id='pages.searchTable.new' defaultMessage='新建'/>
        </Button>, <Button type='primary' hidden={access==='analysis'} key='import' onClick={async () => {
      setShowImport(true);
    }}>
             <FileExcelOutlined/>导入
          </Button>]}/>

         <DrawerForm title='赠品方案' onVisibleChange={setShowCreate} visible={showCreate} formRef={formRef} onFinish={async (values: any) => {
      values.dealerId = dealer.id;
      var val = await saveGift(values);

      if (val.errorCode === '200') {
        message.success('提交成功');
        actionRef.current?.reloadAndRest?.();
        return true;
      } else {
        message.error(val.errorMessage);
        return false;
      }
    }}>
            <ProForm.Group>
              <ProFormText width='xl' name='cnName' label='客户' disabled placeholder='请选择客户' rules={[{
          required: true
        }]}/>
                <Button type='primary' key='primary' style={{
          marginTop: '4px'
        }} onClick={() => {
          setDealDialog(true);
        }}>选择客户</Button>
            </ProForm.Group>
            <ProFormSelect width='xl' name='productName' allowClear={false} label='产品名称' options={nameOption} fieldProps={{
        onChange: value => {
          formRef?.current?.setFieldsValue({
            productName: value
          });
          setCodeOption(proData[value]);
          formRef?.current?.setFieldsValue({
            productStandard: ''
          });
        }
      }}>

            </ProFormSelect>
            <ProFormSelect width='xl' name='productStandard' label='产品型号' options={codeOption}>

            </ProFormSelect>
           <ProFormDigit min={-10000} name='productNum' label='产品数量' placeholder='请输入产品数量' width='md' rules={[{
        required: true
      }]}/>
           <ProFormDatePicker name='effectData' label='截止日期' placeholder='请输入截止日期' width='md' rules={[{
        required: true
      }]}/>
           <ProFormTextArea name='remark' placeholder='请输入' label='备注' fieldProps={{
        showCount: true,
        maxLength: 200
      }}/>
         </DrawerForm>
         <DealerDialog mode='single' onCancel={() => {
      setDealDialog(false);
    }} onSubmit={async value => {
      setDealer(value[0]);
      formRef?.current?.setFieldsValue({
        cnName: value[0].cnName
      });
      setDealDialog(false);
    }} modalVisible={dealDialog} values={[]} >
        </DealerDialog>
         <ModalForm title='赠品导入' onVisibleChange={v => {
      setShowImport(v);
    }} modalProps={{
      destroyOnClose: true,
      forceRender: true
    }} visible={showImport} onFinish={async (values: any) => {
      console.log(values);
      return true;
    }}>
             <div style={{
        margin: '10px 0 20px 0'
      }} ><a href='/xwyl/attach/dealerGift.xlsx' download='赠品模板.xlsx'><Button type='primary'> <FileExcelOutlined/>赠品模板下载</Button></a></div>
            <ProFormUploadDragger label='选择excel上传' name='file' action='/xwyl/dealerGift/dealerGiftImport' fieldProps={{
        name: 'file',
        headers: {
          'authorization': (sessionStorage.getItem('token') as string)
        }
      }} max={1} onChange={onFileUpload}/>

         </ModalForm>

         <Modal visible={errorVisible} title='导入错误提示' width={800} footer={null} destroyOnClose={true} onCancel={handleCancel} >
          <Table dataSource={errInfo} style={{
        height: 400
      }} columns={errorColumn} pagination={false} rowKey='rownum'></Table>
        </Modal>
        <ModalForm title='编辑' onVisibleChange={v => {
      setEditFlag(v);
    }} modalProps={{
      destroyOnClose: true,
      forceRender: true
    }} visible={editFlag} onFinish={async (values: any) => {
      var val = await giftEdit({
        effectData: values.effectData,
        id: editModel?.id
      });

      if (val.errorCode === '200') {
        actionRef.current?.reloadAndRest?.();
        return true;
      } else {
        message.error('修改失败');
        return false;
      }
    }}>
             <ProFormDatePicker name='effectData' initialValue={editModel?.effectData} label='截止日期' placeholder='请输入截止日期' width='md' rules={[{
        required: true
      }]}/>
         </ModalForm>
         <Spin spinning={spinningFlag} style={{
      transform: 'translate(-50%:-50%)',
      left: '50%',
      top: '50%',
      position: 'absolute'
    }}/>
  </PageContainer>;
});